﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

/*
 * Christiaan Rakowski
 * CFProxy - Content Filtering Proxy
 */

namespace CFProxy
{
	class Settings
	{
		/// <summary>
		/// The Port on which the server will listen
		/// </summary>
		public static int Port { get; private set; }
		public static string ErrorPage { get; private set; }

		/// <summary>
		/// Read the settings from the file
		/// </summary>
		/// <param name="path">Path to the Config.xml configuration file</param>
		public static void ReadSettings(string path)
		{
			try
			{
				XmlTextReader reader = new XmlTextReader(path);
				string element = "";
				while (reader.Read())
				{
					if (reader.NodeType == XmlNodeType.Element)
					{
						element = reader.Name;
					}
					if (reader.NodeType == XmlNodeType.Text)
					{
						if (element == "Port")
						{
							int p = -1;
							if (Int32.TryParse(reader.Value, out p))
							{
								Port = p;
							}
							else
							{
								throw new Exception(String.Format("Invalid Port: {0}", reader.Value));
							}
						}
						else if (element == "ErrorPage")
						{
							using(StreamReader s = new StreamReader(reader.Value))
							{
								string line = s.ReadToEnd();
								if (line != null)
								{
									ErrorPage = line;
								}
								else
								{
									throw new Exception(String.Format("Invalid ErrorPage: {0}", reader.Value));
								}
							}
						}
					}
				}
			}
			catch (Exception e)
			{
				Console.WriteLine("Error while parsing configuration file {0}, {1}", path, e.Message);
			} 
		}

	}
}
